package com.rdc.jiajiadictionary.notebook;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.cardview.widget.CardView;
import androidx.core.app.NotificationCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.rdc.jiajiadictionary.R;
import com.rdc.jiajiadictionary.adapter.NotebookAdapter;
import com.rdc.jiajiadictionary.bean.Word;

import java.util.ArrayList;
import java.util.List;

import static com.rdc.jiajiadictionary.adapter.NotebookAdapter.ALL_CHECKED;
import static com.rdc.jiajiadictionary.adapter.NotebookAdapter.NO_CHECKBOX;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link NotebookFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class NotebookFragment extends Fragment implements View.OnClickListener,NotebookViewInterface{

    private boolean isAllChecked = false;
    private FrameLayout backIv;
    private FrameLayout deleteIv;
    private LinearLayout listLl;
    private TextView sortTv;
    private RecyclerView recyclerView;
    private Context context;
    private NotebookPresenter notebookPresenter;
    public CardView chooseCv;
    private TextView cancelTv;
    private TextView deleteTv;
    private TextView allTv;
    private List<String> wordsName = new ArrayList<>();

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public NotebookFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment NotebookFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static NotebookFragment newInstance(String param1, String param2) {
        NotebookFragment fragment = new NotebookFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        notebookPresenter.start();
        chooseCv.setVisibility(View.GONE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.notebook_fragment, container, false);
        backIv = (FrameLayout) view.findViewById(R.id.iv_Back);
        deleteIv = (FrameLayout) view.findViewById(R.id.iv_delete);
        listLl = (LinearLayout) view.findViewById(R.id.ll_list);
        sortTv = (TextView) view.findViewById(R.id.tv_sort);
        recyclerView = (RecyclerView) view.findViewById(R.id.recycle_notebook);
        chooseCv = (CardView) view.findViewById(R.id.cv_choose);
        cancelTv = (TextView) view.findViewById(R.id.tv_cancel);
        deleteTv = (TextView) view.findViewById(R.id.tv_delete);
        allTv = (TextView) view.findViewById(R.id.tv_all);

        backIv.setOnClickListener(this);
        deleteIv.setOnClickListener(this);
        listLl.setOnClickListener(this);
        cancelTv.setOnClickListener(this);
        deleteTv.setOnClickListener(this);
        allTv.setOnClickListener(this);

        new NotebookPresenter(this,context);

        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_list:
                if (sortTv.getText() == "默认排序"){
                    sortTv.setText("字母排序");
                    notebookPresenter.displayNotebookByAlphabet(NO_CHECKBOX);
                } else {
                    sortTv.setText("默认排序");
                    notebookPresenter.displayNotebookByDefault(NO_CHECKBOX);
                }
                chooseCv.setVisibility(View.GONE);
                break;
            case R.id.iv_Back:
                getActivity().finish();
                break;
            case R.id.iv_delete:
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                AlertDialog alertDialog;
                builder.setTitle("友情提示");
                builder.setMessage("确定要清空“我的生词本吗”?");
                builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                builder.setNeutralButton("清空", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        notebookPresenter.deleteAllNotebook();
                        notebookPresenter.displayNotebookByDefault(NO_CHECKBOX);
                        chooseCv.setVisibility(View.GONE);
                    }
                });
                builder.show();
//                alertDialog = builder.create();
//                alertDialog.show();
                break;
            case R.id.tv_cancel:
                chooseCv.setVisibility(View.GONE);
                if (sortTv.getText() == "默认排序"){
                    notebookPresenter.displayNotebookByAlphabet(NO_CHECKBOX);
                } else {
                    notebookPresenter.displayNotebookByDefault(NO_CHECKBOX);
                }
                wordsName.clear();
                break;
            case R.id.tv_delete:
                builder = new AlertDialog.Builder(context);
                builder.setTitle("友情提示");
                builder.setMessage("确定要从“生词本”中删除所选单词吗?");
                builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                builder.setNeutralButton("删除", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        for (int i = 0;i < wordsName.size();i++){
                            notebookPresenter.deleteWordFromNotebook(wordsName.get(i));
                        }
                        Toast.makeText(context, "已将选中的单词从生词本中移除", Toast.LENGTH_SHORT).show();
                        notebookPresenter.displayNotebookByDefault(NO_CHECKBOX);
                        chooseCv.setVisibility(View.GONE);
                        wordsName.clear();
                    }
                });
                builder.show();

                break;
            case R.id.tv_all:
                if (isAllChecked){
                    notebookPresenter.displayNotebookByDefault(-3);
                    isAllChecked = false;
                }else {
                    notebookPresenter.displayNotebookByDefault(ALL_CHECKED);
                    isAllChecked = true;
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void setPresenter(NotebookPresenter presenter) {
        this.notebookPresenter = presenter;
    }

    /**
     * RecycleView子项适配，实现子项点击的回调接口
     * @param words
     */
    @Override
    public void adaptNotebookRecycleView(List<Word> words,int visible) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        NotebookAdapter notebookAdapter = new NotebookAdapter(words,visible);
        ;
//        if (visible == NO_CHECKBOX ){
//            notebookAdapter = new NotebookAdapter(words);
//        } else {
//        }
        notebookAdapter.setOnItemClickListener(new NotebookAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                //子项点击时跳转到单词具体信息
                Word word = words.get(position);
                Bundle bundle = new Bundle();
                bundle.putSerializable("word",word);
                Intent intent = new Intent(getActivity(),NotebookItemActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onPlayClick(int position) {
                Word word = words.get(position);
                String url = null;
                ConnectivityManager connectionManager = (ConnectivityManager)
                        getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
                if (networkInfo != null && networkInfo.isAvailable()) {
                    url = word.getPh_am_mp3();
                } else {
                    if(context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){

                    }else {
                        url = word.getDownloadPath();
                    }
                }
                if (url != null){
                    notebookPresenter.play(url);
                }else {
                    Toast.makeText(context, "当前没有网络，且无法读取本地数据", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onLongClick(int position) {
                chooseCv.setVisibility(View.VISIBLE);
                adaptNotebookRecycleView(words,position);
            }
            @Override
            public void onCheckedChange(int position,boolean isChecked) {
                Word word = words.get(position);
                if (isChecked){
                    wordsName.add(word.getWord_name());
                }else {
                    wordsName.remove(word.getWord_name());
                }
            }

        });
        recyclerView.setAdapter(notebookAdapter);
    }
}

